from util.ExcelProcess_ver2 import read_online_excel
from util.KdocsDownload import kdocs_download
import numpy as np
import datetime
from util.ExcelProcess_ver2 import post_action
'''
1. 保存在线的excel文档
'''
def saveKdocs():
    excel_data = kdocs_download()
    np_data = read_online_excel(excel_data)
    print(np_data)
    np.save('excel_data', np_data)
'''
2. 读取保存的excel内容
'''
# np_data = np.load('excel_data.npy')
# print(np_data)
'''
3. 选择符合条件的内容
'''
def gen_eff_content(today, raw_data, start, end):
    # raw_data = np.load('excel_data.npy')
    # raw_data[11,5] = '2020/11/14'
    # time_interval = 2 # 时间间隔设为2天
    # current_day = datetime.datetime.today()
    # today = datetime.datetime(current_day.year, current_day.month, current_day.day)
    # today = datetime.datetime(2020, 11, 9)

    test = {} # 测试
    run = {} # 运行
    online = {} # 上线

    '''
    数据字典设计：
    {'person' : {'time' : [plmp1, plmp2, plmp3,...]}}
    |<- 姓名->|  |<----------  content-------------->|
    '''

    for row in range(1, len(raw_data)):
        # 第一行是表头, 所以从1开始： ['排期摘要' '排期编号' '排期负责人' '计划移交测试日期' '计划移交运行日期' '计划移交上线日期']
        row_data = raw_data[row]
        for i in [3, 4, 5]:
            time = datetime.datetime.strptime(row_data[i], '%Y/%m/%d')  # 2020-09-02 00:00:00
            person = row_data[2]
            if (start <= ((time - today).days) <= end):
                '''
                    start | end |       对应项目
                    -------------------------------------
                       0  |  1  |        近两天
                       3  |  4  | 今天周五，下周一周二的项目
                       7  |  11 |    下一周的项目汇总
                    -------------------------------------
                '''
                if i == 3: # 写入计划移交测试日期的字典中
                    if person in test.keys():
                        content = test[person]
                        try:
                            plmp = content[row_data[i]] # 比如当前日期是13号，14号也会进到这里，但是字典中没有，就会报错
                        except:
                            content[row_data[i]] = [row_data[0]]
                            test[person] = content
                        else:
                            plmp.append(row_data[0])
                            content[row_data[i]] = plmp
                            test[person] = content
                    else:
                        content = {'%s'%row_data[i] : [row_data[0]]}
                        # test = {'%s'%person : content}
                        test['%s' % person] = content
                elif i == 4:
                    if person in run.keys():
                        content = run[person]
                        try:
                            plmp = content[row_data[i]] # 比如当前日期是13号，14号也会进到这里，但是字典中没有，就会报错
                        except:
                            content[row_data[i]] = [row_data[0]]
                            run[person] = content
                        else:
                            plmp.append(row_data[0])
                            content[row_data[i]] = plmp
                            run[person] = content
                    else:
                        content = {'%s'%row_data[i] : [row_data[0]]}
                        # run = {'%s'%person : content}
                        run['%s'%person] = content
                elif i == 5:
                    if person in online.keys():
                        content = online[person]
                        try:
                            plmp = content[row_data[i]] # 比如当前日期是13号，14号也会进到这里，但是字典中没有，就会报错
                        except:
                            content[row_data[i]] = [row_data[0]]
                            online[person] = content
                        else:
                            plmp.append(row_data[0])
                            content[row_data[i]] = plmp
                            online[person] = content
                    else:
                        content = {'%s'%row_data[i] : [row_data[0]]}
                        # online = {'%s'%person : content}
                        online['%s'%person] = content
    print('test字典内容：', test.keys(), test.values())
    print('===============')
    print('run字典内容：', run.keys(), run.values())
    print('===============')
    print('online字典内容：', online.keys(), online.values())
    print('===============')
    # dict = {"liuxiaoxiang ": "哈哈哈", "xxxx":"xfdsuahf"}
    # print(dict.keys(), dict.values())
    #
    # return test, run, online
    return test, run, online

'''
此函数用来生成推送的字符串
'''
def push_data(today, test, run, online, flag):
    if flag == 1:
        # 近两天的项目
        push_content = r"## 近两天项目排期提醒\n"
    if flag == 2:
        # 今日周五，下周一周二的项目
        push_content = r"## 今日周五，下周一有项目排期提醒，请相关人员注意\n"
    if flag == 3:
        # 下周整个排期安排
        push_content = r"## 下周里程碑节点提醒小助手\n"

    if bool(test):
        if flag == 3:
            push_content += r"### 以下项目将于下周【<font color=\"warning\">计划移交测试</font>】\n\n"
        else:
            push_content += r"### 以下项目即将【<font color=\"warning\">计划移交测试</font>】\n\n"
        for person, content in test.items():
            str = ''
            for time, plmp in content.items():
                for index in range(len(plmp)):
                    str += '>' + '%d'%(index+1) + '.' + plmp[index] + r'\n'
                    str += '>' + '**%s%s**'%(time, datetime_warn(today, time)) + r'\n'
            push_content += str
            push_content += r'<font color=\"info\">@' + person + r'</font>\n\n'
    if bool(run):
        if flag == 3:
            push_content += r"### 以下项目将于下周【<font color=\"warning\">计划移交运行</font>】\n\n"
        else:
            push_content += r"### 以下项目即将【<font color=\"warning\">计划移交运行</font>】\n\n"
        for person, content in run.items():
            str = ''
            for time, plmp in content.items():
                for index in range(len(plmp)):
                    str += '>' + '%d'%(index+1) + '.' + plmp[index] + r'\n'
                    str += '>' + '**%s%s**'%(time, datetime_warn(today, time)) + r'\n'
            push_content += str
            push_content += r'<font color=\"info\">@' + person + r'</font>\n\n'
    if bool(online):
        if flag == 3:
            push_content += r"### 以下项目将于下周【<font color=\"warning\">计划上线</font>】\n\n"
        else:
            push_content += r"### 以下项目即将【<font color=\"warning\">计划上线</font>】\n\n"
        for person, content in online.items():
            str = ''
            for time, plmp in content.items():
                for index in range(len(plmp)):
                    str += '>' + '%d'%(index+1) + '.' + plmp[index] + r'\n'
                    str += '>' + '**%s%s**'%(time, datetime_warn(today, time)) + r'\n'
            push_content += str
            push_content += r'<font color=\"info\">@' + person + r'</font>\n\n'
    print('推送内容：',push_content)
    return push_content

def datetime_warn(today, time):
    time = datetime.datetime.strptime(time, '%Y/%m/%d')  # 2020-09-02 00:00:00
    # current_day = datetime.datetime.today()
    # today = datetime.datetime(current_day.year, current_day.month, current_day.day)
    # today = datetime.datetime(2020, 11, 9)
    interval = (time - today).days


    if interval == 0:
        warn_str = '（今天！）'
    elif interval == 1:
        warn_str = '（明天）'
    elif interval == 3:
        warn_str = '（下周一）'
    elif interval == 4:
        warn_str = '（下周二）'
    else:
        warn_str = '（下周%s）'%switch_num(str(time.isoweekday()))

    print('datatime_warn日志：', time, '间隔:', interval, '提醒类型：', warn_str)
    return warn_str

def switch_num2(num):
    # 将阿拉伯数字转换为汉字
    s = '零一二三四五六七' # 这种写法必须从零开始，不然会出越界异常
    for c in '01234567':
        num = num.replace(c, s[eval(c)]) # eval表达式表示输出c，这里写成int(c)也可以， 表示把num中的c替换成s[c]
    return num
def switch_num(num):
    # 将将阿拉伯数字转换为汉字
    week_dic = {'1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七'}
    return week_dic[num]

def push_everyDay(today, URL, raw_data):
    # 近两天的项目提醒推送，每天都要进行
    test,run,online = gen_eff_content(today, raw_data, 0, 1)
    if bool(test) or bool(run) or bool(online):
        post_action(URL, push_data(today, test, run, online, 1))
    if not bool(test) and not bool(run) and not bool(online):
        post_content= r"## 今日暂无排期安排\n"
        post_action(URL, post_content)

def push_friday(today, URL, raw_data):
    # 在周五的时候推送下周一周二的项目
    test,run,online = gen_eff_content(today, raw_data, 3, 4)
    if bool(test) or bool(run) or bool(online):
        post_action(URL, push_data(today, test, run, online, 2))
    if not bool(test) and not bool(run) and not bool(online):
        post_content= r"## 下周一周二暂无排期安排\n"
        post_action(URL, post_content)

def push_nextWeek(today, URL, raw_data):
    # 在周一的时候推送下一周所有的项目
    test,run,online = gen_eff_content(today, raw_data, 7, 11)
    if bool(test) or bool(run) or bool(online):
        post_action(URL, push_data(today, test, run, online, 3))
    if not bool(test) and not bool(run) and not bool(online):
        post_content= r"## 下周暂无排期安排\n"
        post_action(URL, post_content)




# 单人推送测试机器人
URL = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3e416556-8bad-4ed8-809e-eca2df70e85c'

# 行员群
# URL = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6cc5e84f-b163-47c5-b1ce-ec3d75bccfc0'

# 对公线上融资平台开发群
# URL = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=69280f46-4747-4774-a35b-a537eebc9818'


if __name__ == '__main__':

    # 当有排期变更 更新保存Kdoc文档
    # saveKdocs()

    current_day = datetime.datetime.today()
    today = datetime.datetime(current_day.year, current_day.month, current_day.day)
    # today = datetime.datetime(2020, 11, 26)

    raw_data = np.load('excel_data.npy')

    # 每次跑完一定要注释掉行员群的URL！！！
    push_nextWeek(today, URL, raw_data)
    push_everyDay(today, URL, raw_data)
    # push_friday(today, URL, raw_data)
